package com.weiz.example01.controller;

import com.weiz.example01.service.InfluxDBService;
import org.influxdb.dto.QueryResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/influxdb")
public class InfluxDBController {

    @Autowired
    private InfluxDBService influxDBService;

    @RequestMapping("/save")
    public void save() {
        String measurement = "tomcat_access_log";

        Map<String, String> tags = new HashMap<>();
        tags.put("host", "172.16.10.2");
        tags.put("cpu", "0");

        Map<String, Object> fields = new HashMap<>();
        fields.put("cpu usage", 0.22);
        fields.put("memory usage", 0.56);
        influxDBService.insert(measurement, tags, fields);
    }

    @RequestMapping("/getdata")
    public List<Map<String, Object>> getdata() {
        String command = "select * from tomcat_access_log";

        QueryResult queryResult = influxDBService.query(command);
        List<Map<String, Object>> result = influxDBService.queryResultProcess(queryResult);

        return result;
    }
}
